package com.rt.tmpt.controller.springmvc.admin;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.rt.tmpt.dto.A3MenuDto;
import com.rt.tmpt.dto.Result;
import com.rt.tmpt.service.IMenuService;
import com.rt.tmpt.service.IOperationlogService;
import com.rt.tmpt.utils.DateTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "用户控制类")
@Controller
@RequestMapping("/admin123/right_v2")
@Slf4j
public class MenuAction {

    @Resource
    private IOperationlogService operationlogService;
    @Resource
    private IMenuService menuService;


    /**
     * Vue 完成对接
     * 用户角色 / 权限分配
     * 查出所有菜单结构
     *
     * @return
     */
    @PreAuthorize("hasAuthority('menu:query')")
    @RequestMapping(value = "/menuAjax_menuTree4JustMenu")
    @ResponseBody
    public Result menuTree4JustMenu(String id) {
        Result result = new Result();
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("from", "MenuFromRoleMag");
            paramMap.put("id", id); // 表示哪个menuId作为第1级树。 空：表示从顶开始查
            return menuService.queryMenus4RoleConf(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return result.fault();
        }

    }

    /**
     * Vue
     * 添加菜单项
     *
     * @param menuDto
     * @param optType
     * @param pid     : parentId
     * @return
     */
    @ApiOperation("添加权限项")
    @PreAuthorize("hasAuthority('menu:add-edit')")
    @PostMapping(value = "/menuAjax_addeditMenuNode")
    @ResponseBody
    public Result addeditAuthNode(String _userId, A3MenuDto menuDto, String optType, String pid) {
        Result resultObj = new Result();
        try {
            if ("add".equals(optType)) {
                //添加
                menuDto.setId(null);
                menuDto.setCompanyId(0L);
                menuDto.setCreatemanId(Long.parseLong(_userId));
                menuDto.setCreateDate(DateTool.getCurTimestamp());
                menuDto.setDeleteFlag(0);
                menuDto.setModifymanId(0L);
                menuDto.setHasDataLimit(0);
                menuDto.setCompanyId(0L);
                menuDto.setDeleteFlag(0);
                menuDto.setSort(0);
                menuDto.setType(0);
                long parantId = 0;//根节点
                parantId = Long.parseLong(pid);
                menuDto.setModifymanId(Long.parseLong(_userId));
                menuDto.setModifyDate(DateTool.getCurTimestamp());
                resultObj = menuService.addMenu(menuDto, parantId);
            } else if ("edit".equals(optType)) {
                //修改
                if (menuDto.getHasDataLimit() == null) menuDto.setHasDataLimit(0);
                if (menuDto.getSort() == null) menuDto.setSort(0);
                if (menuDto.getType() == null) menuDto.setType(0);
                resultObj = menuService.modifyMenuById(menuDto);
            } else {
                resultObj.fault("失败：没有相应操作类型");
            }
        } catch (Exception e) {
            resultObj.fault("出错:" + e.getLocalizedMessage());
            e.printStackTrace();
        }

        return resultObj;
    }


    /**
     * Vue
     * 拖拽表格，批量更新菜单顺序
     *
     * @return
     */
    @ApiOperation("拖拽表格，批量更新菜单顺序")
    @PreAuthorize("hasAuthority('menu:add-edit')")
    @PostMapping(value = "/batchUpdateMenusSort")
    @ResponseBody
    public Result batchUpdateMenusSort(@RequestBody String jsonListStr) {
        Result resultObj = new Result();
        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonListStr);
            List<A3MenuDto> a3MenuDtoList = JSON.parseArray(jsonObject.getString("jsonListStr"), A3MenuDto.class);
            resultObj = menuService.batchUpdateMenusSort(a3MenuDtoList);

        } catch (Exception e) {
            resultObj.fault("出错:" + e.getLocalizedMessage());
            e.printStackTrace();
        }

        return resultObj;
    }


    @PreAuthorize("hasAuthority('menu:add-edit')")
    @PostMapping(value = "/publishMenu")
    @ResponseBody
    public Result publishMenu(@RequestBody Map<String, Object> map, String _userId) {
        Result resultObj = new Result();
        try {
            Integer pId = (Integer) map.get("pId");
            Map<String, Object> menuMap = (Map) map.get("menuJson");

            resultObj = menuService.publishMenu(pId, menuMap, Long.parseLong(_userId));

        } catch (Exception e) {
            resultObj.fault("出错:" + e.getLocalizedMessage());
            e.printStackTrace();
        }

        return resultObj;
    }


    /**
     * Vue
     * 删除菜单节点
     *
     * @param id
     * @return
     */
    @ApiOperation("删除菜单节点")
    @PreAuthorize("hasAuthority('menu:add-edit')")
    @PostMapping(value = "/menuAjax_removeMenuNode")
    @ResponseBody
    public Result removeMenuNode(String id) {
        Result resultObj = new Result();
        try {
            resultObj = menuService.removeMenuById(Long.parseLong(id));
        } catch (Exception e) {
            resultObj.fault("出错:" + e.getLocalizedMessage());
            e.printStackTrace();
        }
        return resultObj;
    }

    /**
     * Vue
     * 删除菜单节点
     *
     * @param id
     * @return
     */
    @ApiOperation("删除菜单节点，接联删除")
    @PreAuthorize("hasAuthority('menu:add-edit')")
    @PostMapping(value = "/menuAjax_removeMenuNode4AllNodes")
    @ResponseBody
    public Result removeMenuNode4AllNodes(String id) {
        Result resultObj = new Result();
        try {
            resultObj = menuService.removeMenu4AllNodesById(Long.parseLong(id));
        } catch (Exception e) {
            resultObj.fault("出错:" + e.getLocalizedMessage());
            e.printStackTrace();
        }
        return resultObj;
    }

    /**
     * 菜单管理功能（增删改查）
     * 查出所有菜单结构
     * @return
     */
	/*@PreAuthorize("hasAuthority('menu:query')")
	@RequestMapping(value = "/menuAjax_menuTree4MenuUrls")
	@ResponseBody
	public String menuTree4MenuUrls(String id){
		Result resultObj = new Result();
		String r;
		try{
			Map<String,Object> paramMap = new HashMap<String, Object>();
			paramMap.put("from","MenuMag");
			paramMap.put("id",id);
			resultObj = menuService.queryMenus4RoleConf(paramMap);
			return new Gson().toJson(resultObj.getMap().get("list"));
		}catch (Exception e) {
			r = "出错";
			e.printStackTrace();
			resultObj.fault(r);
			return r;
		}
	}*/

    /**
     * 模板管理生成二级菜单中，一级菜单的选择
     * 查出所有菜单结构
     *
     * @return
     */
    @PreAuthorize("hasAuthority('menu:query')")
    @RequestMapping(value = "/menuAjax_menuTree4JustMenuParent")
    @ResponseBody
    public String menuTree4JustMenuParent(String id) {
        Result resultObj = new Result();
        String r;
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("id", id);
            paramMap.put("from", "OneLevel");
            resultObj = menuService.queryMenus4RoleConf(paramMap);

            String json = new Gson().toJson(resultObj.getMap().get("list"));
            log.debug("menuAjax_menuTree4JustMenuParent -json:" + json);
            return json;

        } catch (Exception e) {
            r = "出错";
            e.printStackTrace();
            resultObj.fault(r);
            return r;
        }
    }


    /**
     * 用户菜单JSON
     *
     * @return
     * @Param userId: get it from filter, parse token
     */
    @ApiOperation("首页菜单栏，菜单列表")
    @PreAuthorize("hasAuthority('menu:query')")
    @GetMapping(value = "/menuAjax_queryMenusByUser")
    @ResponseBody
    public Result queryMenusByUser(String _userId) {
        Result result = menuService.queryMenusByUser(Long.parseLong(_userId));
        return result;
    }


    /*

     */
/**
 * 重新生成源码
 * @return
 *//*

	@PreAuthorize("hasAuthority('menu:code')")
	@RequestMapping(value = "/menuAjax_recoding", produces = "application/json; charset=utf-8")
	@ResponseBody
	public String recoding(String keyRandom, String sourceType,
                           HttpServletRequest request, HttpServletResponse response){
		Result resultObj = new Result();
		try{
			List<String> keyRandomList = new ArrayList<String>();
			keyRandomList.add(keyRandom);
			*/
/*FreemarkerGen freemarkerGen = new FreemarkerGen();
			freemarkerGen.execute(keyRandomList,Integer.parseInt(sourceType));*//*

			resultObj.success();
		}catch (Exception e) {
			resultObj.fault("出错:"+e.getLocalizedMessage());
			e.printStackTrace();
		}
		return new Gson().toJson(resultObj.getMap());
	}


*/

    /*

     */
/**
 * 菜单换位子
 * @param id_change_position
 * @param menu1_id_change_position
 * @param request
 * @param response
 * @return
 *//*

	@PreAuthorize("hasAuthority('menu:add-edit')")
	@RequestMapping(value = "/changeMenuToMenu1", produces = "application/json; charset=utf-8")
	@ResponseBody
	public String changeMenuToMenu1(long id_change_position, long menu1_id_change_position,
                                    HttpServletRequest request, HttpServletResponse response){
		Result resultObj = new Result();
		try{
			resultObj = menuService.changeMenuToMenu1(id_change_position, menu1_id_change_position);
		}catch (Exception e) {
			resultObj.fault("出错:"+e.getLocalizedMessage());
			e.printStackTrace();
		}

		return new Gson().toJson(resultObj.getMap());
	}
*/


}
